//
//  DepoistInputItem2Cell.swift
//  d11
//
//  Created by peale on 2018/10/20.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
typealias Money2ChangeBlock = (_ money: String,_ type:Int) -> Void
class DepoistInputItem2Cell: UITableViewCell,UITextFieldDelegate {
    var bgImgView : UIImageView?
    var iconImgView : UIImageView?
    var titleLabel : UILabel?
    var icon2ImgView : UIImageView?
    var moneyField : UITextField?
    var lineView : UIView?
   // var hintLabel : UILabel?
    var depoistMoneyListView :DepoistMoneyListView?
    var slideImgView : UIImageView?
    var images = [UIImage]()
    var selectIndex :Int = -1  //按钮选中的下标
    var rangeLimitLabel:UILabel?
    var money2ChangeBlock: Money2ChangeBlock?
    func callChangeBlock(_ block: @escaping Money2ChangeBlock) {
        
        money2ChangeBlock = block
    }
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func setUpUI() -> Void {
        for i in 1...11 {
              images.append(imageNamed("icon_depoist_slide_\(String(i))")!)
        }
        self.backgroundColor  = UIColor.clear
        self.selectionStyle = UITableViewCell.SelectionStyle.none
        self.bgImgView = UIImageView.init()
        self.bgImgView?.isUserInteractionEnabled = true
        self.bgImgView?.image = imageNamed("icon_depoist_money_input_bg_double")?.resizableImage(withCapInsets: UIEdgeInsets(top: 5, left: 30, bottom: 5, right: 30),resizingMode: .stretch) //左右15像素的部分不变，中间部分来拉伸
        self.contentView.addSubview(bgImgView!);
        self.bgImgView?.snp.makeConstraints{(make) in
            make.width.equalToSuperview()
            make.height.equalTo(215)
            make.centerX.equalTo(self.contentView)
        }
        
        self.iconImgView = UIImageView.init()
        self.iconImgView?.image = imageNamed("icon_depoist_money_icon")
        self.bgImgView?.addSubview(self.iconImgView!)
        self.iconImgView?.snp.makeConstraints{(make) in
            make.left.equalToSuperview().offset(22)
            make.width.equalTo(19)
            make.height.equalTo(20)
            make.top.equalToSuperview().offset(30)
        }
        self.titleLabel = UILabel.init()
        self.titleLabel?.text = "充值金额"
        self.titleLabel?.textColor = HexRGBAlpha(0x333333, 1)
        self.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        self.titleLabel?.textAlignment = NSTextAlignment.left
        self.bgImgView?.addSubview(self.titleLabel!)
        
        self.titleLabel?.snp.makeConstraints{(make) in
            make.left.equalTo((self.iconImgView?.snp.right)!).offset(15)
            make.width.equalTo(100)
            make.height.equalTo(20)
            make.top.equalTo(self.iconImgView!)
        }
        self.icon2ImgView = UIImageView.init()
        self.icon2ImgView?.image = imageNamed("icon_depoist_money_input_icon_top")
        self.bgImgView?.addSubview(self.icon2ImgView!)
        self.icon2ImgView?.snp.makeConstraints{(make) in
            make.right.equalToSuperview().offset(-7)
            make.width.equalTo(93)
            make.height.equalTo(85)
            make.top.equalToSuperview().offset(7)
        }
        
        
        self.moneyField = UITextField.init()
        self.moneyField?.font = UIFont.systemFont(ofSize: 22)
        self.moneyField?.textAlignment = NSTextAlignment.left
        self.moneyField?.keyboardType  = .decimalPad
        self.moneyField?.placeholder = "可手动输入充值金额"
        self.moneyField?.delegate = self
        self.bgImgView?.addSubview(self.moneyField!)
        self.moneyField?.addTarget(self, action: #selector(self.actionToChanged(_:)), for: UIControl.Event.editingChanged)
        self.moneyField?.snp.makeConstraints{(make) in
            make.left.equalTo((self.iconImgView?.snp.left)!)
           // make.right.equalTo((self.icon2ImgView?.snp.left)!).offset(-5)
            make.right.equalToSuperview().offset(-5)
            make.top.equalTo((self.titleLabel?.snp.bottom)!).offset(15)
            make.height.equalTo(30)
        }
        
        self.lineView = UIView.init()
        self.lineView?.backgroundColor = HexRGBAlpha(0xF3F3F3, 1)
        self.bgImgView?.addSubview(self.lineView!)
        
        self.lineView?.snp.makeConstraints{(make) in
            make.centerX.equalToSuperview()
            make.width.equalToSuperview().offset(-20)
            make.height.equalTo(0.7)
            make.top.equalTo((moneyField?.snp.bottom)!).offset(10)
        }
    
//        self.hintLabel = UILabel.init()
//        self.hintLabel?.text = "温馨提示:(存款金额后2位数字不可同时为0,例：108元)"
//        self.hintLabel?.textColor = HexRGBAlpha(0xFFCF8D, 1)
//        self.hintLabel?.numberOfLines = 2
//        self.hintLabel?.textAlignment = .left
//        self.hintLabel?.font = UIFont.systemFont(ofSize: 13)
//        self.bgImgView?.addSubview(self.hintLabel!)
//        self.hintLabel?.snp.makeConstraints{(make) in
//            make.width.equalToSuperview().offset(-45)
//            make.left.equalToSuperview().offset(25)
//            make.height.equalTo(35)
//            make.top.equalTo((lineView?.snp.bottom)!).offset(5)
//        }
        //18x18

       let list = [String]()
       self.depoistMoneyListView = DepoistMoneyListView.init(list: list)
        self.bgImgView?.addSubview(self.depoistMoneyListView!)
        self.depoistMoneyListView?.callChangeBlock({(money) in
            if self.money2ChangeBlock != nil {
                 self.moneyField?.text = money
                self.money2ChangeBlock!(money,2)
            }
        })
        self.depoistMoneyListView?.snp.makeConstraints{(make) in
            make.width.equalToSuperview().offset(-65)
            make.height.equalTo(50)
            make.top.equalTo((lineView?.snp.bottom)!).offset(3+10)
            make.left.equalToSuperview().offset(20)
        }
       
        self.slideImgView = UIImageView.init()
        //icon_depoist_money_slide_icon
        self.slideImgView?.image = imageNamed("icon_depoist_slide_11")
        self.slideImgView?.animationImages = self.images
        self.slideImgView?.animationDuration = 1.5
     //  self.slideImgView?.animationRepeatCount = 10
        self.slideImgView?.startAnimating()
        self.bgImgView?.addSubview(self.slideImgView!)
        self.slideImgView?.snp.makeConstraints{(make) in
            make.right.equalToSuperview().offset(-12)
            make.width.equalTo(27)
            make.height.equalTo(18)
            make.centerY.equalTo((depoistMoneyListView?.snp.centerY)!)
        }
        
        self.rangeLimitLabel = UILabel.init()
        self.rangeLimitLabel?.textColor = HexRGBAlpha(0x555555, 1)
        self.rangeLimitLabel?.numberOfLines = 1
        self.rangeLimitLabel?.textAlignment = .left
        self.rangeLimitLabel?.font = UIFont.systemFont(ofSize: 14)
        self.bgImgView?.addSubview(self.rangeLimitLabel!)
        self.rangeLimitLabel?.snp.makeConstraints{(make) in
            make.width.equalToSuperview().offset(-45)
            make.left.equalToSuperview().offset(25)
            make.height.equalTo(20)
            make.top.equalTo((self.depoistMoneyListView?.snp.bottom)!).offset(5)
        }
    }
    
    func  setData(money:String?) -> Void {
        self.moneyField?.text = money
    }
    
    func  setData(money:String?,array:[String]) -> Void {
        self.moneyField?.text = money
        if self.depoistMoneyListView?.arrayList == nil || (self.depoistMoneyListView?.arrayList?.count)! <= 0{
            self.depoistMoneyListView?.arrayList = array
            self.depoistMoneyListView?.collectionView.reloadData()
        }
        
    }
    
    
    func  setData(money:String?,array:[String],rangeLimit:String) -> Void {
        self.moneyField?.text = money
        if self.depoistMoneyListView?.arrayList == nil || (self.depoistMoneyListView?.arrayList?.count)! <= 0{
            self.depoistMoneyListView?.arrayList = array
            self.depoistMoneyListView?.collectionView.reloadData()
        }
       let limitArray =  rangeLimit.components(separatedBy: ",")
        var textString = ""
        if limitArray.count >= 2 {
            textString = "最小金额为:\(limitArray[0]),最大金额为:\(limitArray[1])"
        }else if limitArray.count == 1{
            textString = "最小金额为:\(limitArray[0])"
        }else if limitArray.count == 0{
            textString = rangeLimit
        }
        if self.slideImgView?.isAnimating == false {
            self.slideImgView?.startAnimating()
        }
        self.rangeLimitLabel?.text = textString
       

    }
    @objc func actionToChanged(_ sender: UITextField) -> Void {
        if money2ChangeBlock != nil {
            money2ChangeBlock!(sender.text!,1)
        }
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        /// decimal 全局参数用来控制
        /// 如果是小数文本框则执行下面操作，如果是文字文本框 不需要做任何限制
        //if decimal {
            
            /// 小数点前可以输入 20位
            let Digits = 6
            if textField.text?.contains(".") == false && string != "" && string != "."{
                if (textField.text?.count)! > Digits{
                    return false
                }
            }
            
            let scanner = Scanner(string: string)
            let numbers : NSCharacterSet
            let pointRange = (textField.text! as NSString).range(of: ".")
            
            if (pointRange.length > 0) && pointRange.length < range.location || pointRange.location > range.location + range.length {
                numbers = NSCharacterSet(charactersIn: "0123456789.")
            }else{
                numbers = NSCharacterSet(charactersIn: "0123456789.")
            }
            
            if textField.text == "" && string == "." {
                return false
            }
            /// 小数点后8位
            let remain = 2
            
            let tempStr = textField.text!.appending(string)
            
            let strlen = tempStr.count
            
            if pointRange.length > 0 && pointRange.location > 0{//判断输入框内是否含有“.”。
                if string == "." {
                    return false
                }
                
                if strlen > 0 && (strlen - pointRange.location) > remain + 1 {//当输入框内已经含有“.”，当字符串长度减去小数点前面的字符串长度大于需要要保留的小数点位数，则视当次输入无效。
                    return false
                }
            }
            
            let zeroRange = (textField.text! as NSString).range(of: "0")
            if zeroRange.length == 1 && zeroRange.location == 0 { //判断输入框第一个字符是否为“0”
                if !(string == "0") && !(string == ".") && textField.text?.count == 1 {//当输入框只有一个字符并且字符为“0”时，再输入不为“0”或者“.”的字符时，则将此输入替换输入框的这唯一字符。
                    textField.text = string
                    return false
                }else {
                    if pointRange.length == 0 && pointRange.location > 0 {//当输入框第一个字符为“0”时，并且没有“.”字符时，如果当此输入的字符为“0”，则视当此输入无效。
                        if string == "0" {
                            return false
                        }
                    }
                }
            }
            //        let buffer : NSString!
            if !scanner.scanCharacters(from: numbers as CharacterSet, into: nil) && string.count != 0 {
                return false
            }
            
   //     }
        
        return true
        
    }
}
